import fetch from 'dva/fetch';
import qs from 'qs';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */

export default function request(url, options = {}) {
  // const baseUrl = 'http://localhost:3333/socketIo'; // 本地访问
  const baseUrl =  'https://www.chensai.club/socketIo' // 远程地址
  const requestOptions = Object.assign({
    headers: {
      // 这里也可以使用application/json,body中就要使用JSON.stringfy()进行序列化,但是回进行一次预检查，options/get/post，下面的只会执行一次
      'content-type': 'application/x-www-form-urlencoded'
    },
    // 这里使用的cors跨域，将credentials设置为inlcude，否则不跨域可以将credentials设置为some-origin
    mode: 'cors',
    credentials: 'include', // 跨域情况下，传递cookie
    method: 'get', // 默认get
  }, options);
  const methodType = requestOptions.method;
  if (methodType.toLowerCase() === 'post' || methodType.toLowerCase() === 'put') {
    requestOptions.body = qs.stringify(requestOptions.body);
  }
  return fetch(baseUrl + url, requestOptions)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      const { code } = data;
      if (code === 401) {
        // 401登录过期
        window.location.href = '/#/login';
      }
      return { data };
    })
    .catch(err => ({ err }));
}
